<?php

namespace app\common;

class StsService
{
    protected $url = 'https://sts.aliyuncs.com';
    protected $accessKeySecret;
    protected $accessKeyId;
    protected $roleArn;//指定角色的 ARN ，角色策略权限
    protected $durationSeconds;//指定的过期时间
    protected $config;

    public function __construct()
    {
        $this->config = $config = config('filesystem.alioss');
        $this->accessKeyId = $config['access_key_id'];
        $this->accessKeySecret = $config['access_key_secret'];
        $this->roleArn = $config['role_arn']; // 指定角色的 ARN ，角色策略权限
        $this->durationSeconds = $config['duration_seconds'];
    }

    /*
     * 生成sts授权凭证
    */
    public function getStsAuth()
    {
        // 引入文件，根据自己路径来引入
        require_once __DIR__.'/../../extend/sts-server/aliyun-php-sdk-core/Config.php';

        $iClientProfile = \DefaultProfile::getProfile("cn-shenzhen", $this->accessKeyId, $this->accessKeySecret);

        $client = new \DefaultAcsClient($iClientProfile);

        $request = new \Sts\Request\V20150401\AssumeRoleRequest();

        $request->setRoleSessionName("client_name");

        $request->setRoleArn($this->roleArn);

        $request->setDurationSeconds($this->durationSeconds);

        $response = $client->doAction($request);

        $rows = array();

        $body = $response->getBody();

        $content = json_decode($body);

        if ($response->getStatus() == 200) {
            $rows['statusCode'] = 200;
            $rows['accessKeyId'] = $content->Credentials->AccessKeyId;
            $rows['accessKeySecret'] = $content->Credentials->AccessKeySecret;
            $rows['expiration'] = $content->Credentials->Expiration;
            $rows['securityToken'] = $content->Credentials->SecurityToken;
            $rows['bucket'] = $this->config['bucket'];
            $rows['region'] = $this->config['region'];
        } else {
            $rows['statusCode'] = 500;
            $rows['errorCode'] = $content->Code;
            $rows['errorMessage'] = $content->Message;
        }

        return $rows;
    }

}
